package Client;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.swing.JOptionPane;
import Util.MessageType;
import Util.XMLUtil;

public class LoginConnection extends Thread {
	private String userName;
	private String serverAddress;
	private int port;
	private Login login;
	private InputStream is;
	private OutputStream os;
	private Chatting chatting;
	private Socket socket;

	public LoginConnection(String userName, String serverAddress, int port,
			Login login) {
		this.userName = userName;
		this.serverAddress = serverAddress;
		this.port = port;
		this.login = login;
		if (this.connect2Server(serverAddress, port)) {
			this.login();
		}
	}

	private boolean connect2Server(String serverAddress, int port) {
		try {
			this.socket = new Socket(serverAddress, port);
			is = socket.getInputStream();
			os = socket.getOutputStream();
			return true;
		} catch (Exception e) {
			JOptionPane.showMessageDialog(login, "服务器可能还没启动，请确定服务器正常",
					"无法连接到服务器", JOptionPane.ERROR_MESSAGE);
			return false;
		}
	}

	public String getUserName() {
		return userName;
	}

	public InputStream getIs() {
		return is;
	}

	public OutputStream getOs() {
		return os;
	}

	public void login(){
		try{
			String info = XMLUtil.constructLoginXML(userName);
			os.write(info.getBytes());
			byte[] buf = new byte[5000];
			int length = is.read(buf);
			String response = new String(buf,0,length);
			String result = XMLUtil.extractResult(response);
			if (result.equals("success")){
				this.login.setVisible(false);
				this.chatting = new Chatting("聊天室("+userName+")",this);
				//System.out.println(response);
				this.start();
			}else{
				JOptionPane.showMessageDialog(this.login, "用户名已经存在，请重新输入","登录验证",JOptionPane.WARNING_MESSAGE);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void sendMessage(String message,String type){
		try{
			int t = Integer.parseInt(type);
			String xml = null;
			if (MessageType.C2SMessage == t){
				xml = XMLUtil.constructC2SMessageXML(userName,message);
			}
			
			//
			/*if (MessageType.ServerTextArea == t){
				xml = XMLUtil.constructServerTextAreaXML(userName,message);
			}*/
			
			if (MessageType.ClientClosing == t){
				xml = XMLUtil.constructClientClosingXML(message);
			}
			if(MessageType.C2CMessage==t)
			{
				//@ccc fdjfkjdkas
				int pos = message.indexOf(" ");
				String reciver = message.substring(1, pos);
				String content = message.substring(pos+1);
				xml = XMLUtil.constructC2CMessage(userName, reciver, content);
			}
			os.write(xml.getBytes());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void run(){
		try{
			while(true){
				byte[] buf = new byte[5000]; 
				String message;
				int messageType; 
				int length = is.read(buf);
				 message = new String(buf,0,length); 
				//System.out.println(message);
				 messageType = Integer.parseInt(XMLUtil.extractType(message));
				if (MessageType.UseList == messageType){
					List<String> list = XMLUtil.extractAllUsers(message);
					String users = "";
					for(String user:list){
						users += user + "\n";
					}
					this.chatting.getList().setText(users);
				}
				if (MessageType.S2CMessage == messageType){
					String info = "";
					info += XMLUtil.extractContent(message) + "\n";
					this.chatting.getMessages().setText(this.chatting.getMessages().getText()+info);
				}
				
				//
				if (MessageType.ServerTextArea == messageType){
					String info = "";
					info += XMLUtil.extractContent(message) + "\n";
					this.chatting.getMessages().setText(this.chatting.getMessages().getText()+info);
				}
				//说明对方在把数据返回后，就把socket关闭了，而客户端还在读数据。所以就connection reset。
				
				if (MessageType.ClientClosingConfirm == messageType){
					this.os.close();
					this.is.close();
					this.socket.close();
					break;
				}
				if (MessageType.ServerClosing == messageType){
					JOptionPane.showMessageDialog(chatting, "服务器关闭，即将退出","服务器关闭",JOptionPane.ERROR_MESSAGE);
					System.exit(0);
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		System.exit(0);
	}
}
